<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#" :index="indexMethod"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatusChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              class="table-button"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除角色按钮 -->
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确认删除用户？"
              @onConfirm="deleteUser(scope.row)"
            >
              <el-button
                slot="reference"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                class="table-button"
              ></el-button>
            </el-popconfirm>
            <!-- 分配权限按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" class="table-button"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :total="this.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[2,5,10]"
        :page-size="queryInfo.pagesize"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主题区域 -->
      <el-form :model="addForm" :rules="addFromRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密 码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮 箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮 箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 添加用户 邮箱验证
    var validateEmail = (rule, value, callback) => {
      const reg = new RegExp(
        "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"
      );
      if (value !== "" && !reg.test(value)) {
        callback(new Error("邮箱格式不正确"));
      } else {
        callback();
      }
    };
    return {
      // 获取用户数据列表的参数对象
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        pagesize: 5,
      },
      // 用户列表数据
      userList: [],
      total: 0,
      pagenum: "",
      // 控制添加用户对话框
      addDialogVisible: false,
      // 控制修改用户对话框
      editDialogVisible: false,
      // 添加用户表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加用户表单校验规则
      addFromRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 5 到 20 个字符",
            trigger: "blur",
          },
        ],
        email: [{ validator: validateEmail, trigger: "blur" }],
      },
      // 修改用户信息表单数据
      editForm: {
        id: "",
        username: "",
        email: "",
        mobile: "",
      },
      // 修改用户信息校验规则
      editFormRules: {
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [],
      },
    };
  },
  methods: {
    //   获取用户列表
    getUserList() {
      var _this = this;
      // 将get查询参数定义到data中
      this.$http
        .get("users", { params: _this.queryInfo })
        .then(({ data: res }) => {
          if (res.meta.status !== 200) {
            el - alert(res.meta.msg);
          } else {
            _this.userList = res.data.users;
            _this.total = res.data.total;
            _this.pagenum = res.data.oagenum;
          }
        });
    },
    // 索引列计算方法
    indexMethod(index) {
      return index + 1;
    },
    // 用户状态修改
    userStatusChanged(userInfo) {
      this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`).then(
        ({ data: res }) => {
          if (res.meta.status !== 200) {
            alert(res.meta.msg);
          }
        },
        (res) => {
          alert("用户状态更新失败");
          userInfo.mg_state = !userInfo.mg_state;
        }
      );
    },
    // 分页符函数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 添加用户对话框关闭事件 重置表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户
    addUsers() {
      this.$refs.addFormRef.validate((vaild) => {
        if (!vaild) {
          alert("表单数据不正确");
        } else {
          this.$http.post("users", this.addForm).then(
            ({ data: res }) => {
              if (res.meta.status !== 201) {
                this.$message.error(res.meta.msg);
              } else {
                this.$message.success("用户添加成功");
                this.addDialogVisible = false;
                this.getUserList();
              }
            },
            ({ data: res }) => {
              console.log(res);
              alert("用户创建失败");
            }
          );
        }
      });
    },
    // 弹出修改用户信息对话框
    showEditDialog(userInfo) {
      this.editDialogVisible = true;
      this.editForm.id = userInfo.id;
      this.editForm.username = userInfo.username;
      this.editForm.email = userInfo.email;
      this.editForm.mobile = userInfo.mobile;
    },
    // 修改用户信息
    editUser() {
      this.$refs.editFormRef.validate((vaild) => {
        if (!vaild) {
          this.$message.error("请输入正确的信息");
          return;
        }
        // {data:res}解构赋值并重命名
        // 发送请求修改后台数据
        const params = {
          id: this.editForm.id,
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        };
        this.$http.put(`users/${this.editForm.id}`, params).then(
          ({ data: res }) => {
            if (res.meta.status !== 200) {
              this.$message.error(res.meta.msg);
            } else {
              this.$message.success("修改用户数据成功");
            }
          },
          ({ res: data }) => {
            this.$message.error("修改用户数据失败");
          }
        );

        this.editDialogVisible = false;
        this.getUserList();
      });
    },
    // 编辑用户信息对话框关闭事件 重置表单
    // 点击不同的修改按钮时，关闭的一瞬间会有数据闪烁，因此全部置空
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
      this.editForm.username = "";
      this.editForm.email = "";
      this.editForm.mobile = "";
    },
    // 删除用户
    deleteUser(userInfo) {
      this.$http.delete(`users/${userInfo.id}`).then(
        ({ data: res }) => {
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg);
          } else {
            this.$message.success(`删除用户${userInfo.id}成功`);
            this.getUserList();
          }
        },
        ({ res: data }) => {
          this.$message.error(`删除用户${userInfo.id}失败`);
        }
      );
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}

.table-button {
  margin: 0;
}
</style>